package cn.jietuo.netty.base;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;

/**
 * @author zhangx & jietuo_zx@163.com
 * @version 1.0
 * @date 2021/2/27
 * @description: netty中bytebuf的使用详解
 */
public class NettyByteBuf {

    public static void main(String[] args) {
        // 创建byteBuf对象，该对象内部包含了一个字节数组byte[10]
        // readerIndex / writeIndex / capacity将buffer分为三个区域
        // [0,readerIndex)  已经读取的区域
        // [readIndex,writeIndex) 可读取的区域
        // [writeIndex，capacity) 可写入的区域
        ByteBuf byteBuf = Unpooled.buffer(10);
        System.out.println(byteBuf);
        for (int i = 0; i < 8; i++) {
            byteBuf.writeByte(i);
        }
        System.out.println(byteBuf);
        for (int i = 0; i < 5; i++) {
            // 这个方法不会影响到readerIndex
            byteBuf.getByte(i);
        }
        System.out.println(byteBuf);
        for (int i = 0; i < 6; i++) {
           byteBuf.readByte();
        }
        System.out.println(byteBuf);

        // 使用Unpooled工具类创建ByteBuf
        ByteBuf byteBuf1 = Unpooled.copiedBuffer("Hello,netty!", CharsetUtil.UTF_8);
        if (byteBuf1.hasArray()){
            byte[] array = byteBuf1.array();
            // 将array转成字符串
            System.out.println(new String(array,CharsetUtil.UTF_8));
            System.out.println(byteBuf1);

            System.out.println(byteBuf1.readerIndex());
            System.out.println(byteBuf1.writerIndex());
            System.out.println(byteBuf1.capacity());
            // 可读字节数
            int i = byteBuf1.readableBytes();
        }
    }
}
